import 'dart:async';

import 'package:flutter/material.dart';
import 'package:vibration/vibration.dart';

class TestMusicVibrate extends StatefulWidget {
  @override
  _TestMusicVibrateState createState() => _TestMusicVibrateState();
}

class _TestMusicVibrateState extends State<TestMusicVibrate> {
  Timer _timer;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("TestMusicVibrate"),
      ),
      body: Container(
        child: Column(
          children: [
            RaisedButton(
              onPressed: () {
                _notify();
              },
              child: Text("响铃及振动"),
            ),
            RaisedButton(
              onPressed: () {
                _cancel();
              },
              child: Text("取消"),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _notify() async {
    bool hasVibrator = await Vibration.hasVibrator();
    if (!hasVibrator) {
      print("没有震动权限");
      return;
    }
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (timer.tick == 60) {
        _cancel();
      }
      Vibration.vibrate(duration: 500);
    });
  }

  @override
  void deactivate() {
    _cancel();
    super.deactivate();
  }

  void _cancel() {
    Vibration?.cancel();
    _timer?.cancel();
    _timer = null;
  }
}
